<?php
session_start();

/**
 * Script used to login a user
 */

// Return json encoded data
header ('Content-type: application/json');
require_once '../core/db.php';
define ('SALT', 'ThisIsth3sal7'); // NEVER CHANGE!
define ('SITEKEY', 'ASiteSpecificArbitraryLengthStringThatIsUsedToSeedTheHashingAlgorithm'); //NEVER CHANGE!

$sql = "SELECT * FROM siteUsers WHERE userName=:usrName";
$query = $db -> prepare($sql);
$query -> bindParam(':usrName', $_POST['uname']);
$query -> execute();
$res = $query -> fetch();
if(isset($res['userID'])){
	$uid = $res['userID'];
	$pwd = $uid.$_POST['pwd'].SALT;
	$pwdhashed =  hash_hmac('sha512', $pwd, SITEKEY);
	$sql = "SELECT * FROM siteUsers WHERE userName=:usrName AND password=:pwd";
	$query = $db -> prepare($sql);
	$query -> bindParam(':usrName', $res['userName']);
	$query -> bindParam(':pwd', $pwdhashed);
	$query -> execute();
	$res = $query -> fetch();
	if(isset($res["userName"])){
		session_regenerate_id(true);
		$_SESSION['user'] = $res['userID'];
		echo json_encode(array("ok" => "OK"));
	}else{
		echo json_encode(array("bad_username" => "Incorrect username or password"));
	}
}else{
	echo json_encode(array("bad_username" => "Incorrect username or password"));
}
	

?>